﻿using System.Collections.Generic;
using Startup.Project.Algorithm;
using Startup.Project.Classes;

namespace Startup.Shell.Domain.FunctionalityContracts
{
	public class NewCommandContract : CommandContractBase
	{
		public override string CommandName
		{
			get { return "New"; }
		}

		public override AlgorithmAction[] GetContent(ClassBase dataContextType, StartupProperty property)
		{
			CreateAction create = new CreateAction(new ConstructorDefinition(dataContextType));
			AlgorithmAction[] initializeActions = InitializeObject(create.Result);
			CustomAction saveProperty = new CustomAction(string.Format("{0} = {1};", property.Name, "{0}"), create.Result);

			List<AlgorithmAction> scenario = new List<AlgorithmAction>();
			scenario.Add(create);
			scenario.AddRange(initializeActions);
			scenario.Add(saveProperty);

			return scenario.ToArray();
		}

		private static AlgorithmAction[] InitializeObject(LocalField target)
		{
			List<AlgorithmAction> actions = new List<AlgorithmAction>();
			CustomClass type = (CustomClass)target.Type;

			for (int index = 0; index < type.Properties.Count; index++)
			{
				PropertyDefinition property = type.Properties[index] as PropertyDefinition;

				if (property != null && property.ReturnedType is CustomClass)
				{
					CustomClass parameterType = (CustomClass)property.ReturnedType;
					
					CreateAction create = new CreateAction(parameterType.DefaultConstructor);
					actions.Add(create);

					actions.AddRange(InitializeObject(create.Result));

					SetPropertyValueAction setProperty = new SetPropertyValueAction(target, property, create.Result);
					actions.Add(setProperty);
				}
				else if (property != null && property.ReturnedType is CollectionStandartClass)
				{
					CollectionStandartClass parameterType = (CollectionStandartClass)property.ReturnedType;
					
					CreateAction create = new CreateAction(new ConstructorDefinition(parameterType));
					actions.Add(create);
					
					SetPropertyValueAction setProperty = new SetPropertyValueAction(target, property, create.Result);
					actions.Add(setProperty);
				}
			}

			return actions.ToArray();
		}
	}
}
